package com.example.demo.test;

import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendCallback;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.remoting.exception.RemotingException;
import com.example.demo.utils.UUIDUtil;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

public class AsyncProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("test_group2");
        producer.setNamesrvAddr("47.110.232.77:9876");
        producer.setRetryTimesWhenSendAsyncFailed(0);
        producer.start();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            Message msg = new Message(
                    "TopicA",
                    UUID.randomUUID().toString(),
                    "消息".getBytes(StandardCharsets.UTF_8)
            );
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息:"+sendResult+"已被成功发送");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送抛出异常:"+throwable);
                }
            });
            countDownLatch.countDown();
        }
        countDownLatch.await();
        producer.shutdown();

    }
}
